<template>
  <div class="mine">
    <van-nav-bar
      style="height: 46px; font-size: 12px"
      title="订单确认"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />
    <div class="celladdress">
      <van-cell title="服务地址" icon="location-o" size="large" @click="showPopup" center>
        <template #label>
          <van-row gutter="40" type="flex">
            <van-col span="8">姓名：{{ content[0] }}</van-col>
            <van-col span="8">电话：{{ content[1] }}</van-col>
            <van-col span="12">地址：{{ content[2] }}</van-col>
          </van-row>
        </template>
      </van-cell>
    </div>
    <van-popup v-model="show" position="bottom" :style="{ height: '80%' }">
      <van-address-list
        v-model="chosenAddressId"
        :list="addressList"
        default-tag-text="默认"
        add-button-text="确定"
        @add="confirmaddress(chosenAddressId)"
      />
    </van-popup>
    <div class="cellaorder">
      <van-cell title="订单详情" icon="balance-list-o" size="large">
        <template #label>
          <van-row gutter="40" v-for="orderLine in orderLines.values()" :key="orderLine.productId">
            <van-col span="6">{{ orderLine.productName }}</van-col>
            <van-col span="6">￥{{ orderLine.price }}</van-col>
            <van-col span="6">+{{ orderLine.number }}</van-col>
          </van-row>
          <van-divider
            :style="{
              color: '#cdcdcd',
              borderColor: '#cdcdcd',
              padding: '0 2px',
              background: '#cdcdcd',
            }"
          ></van-divider>
          <van-row>
            <van-col span="6" offset="12">总价：￥{{ total }}</van-col>
          </van-row>
        </template>
      </van-cell>
    </div>
    <div class="celltime">
      <van-cell
        title="服务时间"
        icon="clock-o"
        :value="daytime | dateFormat"
        size="large"
        @click="showPopup2"
      />
    </div>
    <van-popup v-model="show2" position="bottom" :style="{ height: '50%' }">
      <van-datetime-picker
        v-model="currentDate"
        type="datetime"
        title="选择完整时间"
        :min-date="minDate"
        :max-date="maxDate"
        @confirm="confirmtime()"
        @cancel="canceltime()"
      />
    </van-popup>

    <van-button
      color="linear-gradient(to right, #ff6034, #ee0a24)"
      block="true"
      style="
        width: 278px;
        height: 40px;
        border-radius: 22px;
        margin: 30px auto;
        font-size: 15px;
      "
      @click="submit()"
    >确认提交</van-button>
  </div>
</template>

<script>
import { get, post, post_json } from "@/http/axios";
// 引入vuex的辅助函数
import { mapActions, mapState, mapMutations, mapGetters } from "vuex";
export default {
  data() {
    return {
      minDate: new Date(2020, 0, 1),
      maxDate: new Date(2031, 10, 1),
      currentDate: new Date(),
      daytime: "",
      content: [],
      show: false,
      show2: false,
      chosenAddressId: 2300,
      list: [
        {
          id: "1",
          name: "张三",
          tel: "13000000000",
          address: "浙江省杭州市西湖区文三路 138 号东方通信大厦 7 楼 501 室",
          isDefault: true,
        },
        {
          id: "2",
          name: "李四",
          tel: "1310000000",
          address: "浙江省杭州市拱墅区莫干山路 50 号",
        },
      ],
      addressData: {},
    };
  },
  computed: {
    ...mapState("shopcart", ["orderLines"]),
    ...mapGetters("shopcart", ["total"]),
    ...mapState("user", ["userInfo"]),
    addressList() {
      // 筛选地址数据 生成匹配组件的数据
      let addressArr = this.addressData.list;
      let addressList = [];
      if (!addressArr) {
        return;
      }
      addressArr.forEach((item, index) => {
        let addressObj = {};
        (addressObj.id = item.id),
          (addressObj.name = item.username),
          (addressObj.tel = item.telephone),
          (addressObj.address =
            item.province + item.city + item.area + item.address),
          (addressObj.isDefault = item.isDefault);
        addressList.push(addressObj);
      });
      return addressList;
    },
  },
  methods: {
    ...mapActions("user", ["getUserInfo"]),
    ...mapActions("product", ["getAllProductData"]),
    ...mapMutations("shopcart", ["addShopcart", "clearShopcart"]),
    onClickLeft() {
      this.$router.go(-1);
      this.clearShopcart();
    },
    showPopup() {
      this.show = true;
    },
    showPopup2() {
      this.show2 = true;
    },
    confirmtime() {
      this.show2 = false;
      this.daytime = String(this.currentDate);
    },
    canceltime() {
      this.show2 = false;
    },
    async getAddressData() {
      let data = {
        page: 1,
        pageSize: 100,
      };
      let res = await get("/address/pageQuery", data);
      // 将拿到的数据赋值给轮播图数组
      this.addressData = res.data.data;
      return res;
    },
    confirmaddress(chosenAddressId) {
      let addressData = {};
      for (let index = 0; index < this.addressList.length; index++) {
        addressData = this.addressList[index];
        if (chosenAddressId == addressData.id) {
          this.content[0] = addressData.name;
          this.content[1] = addressData.tel;
          this.content[2] = addressData.address;
        }
      }
      this.show = false;
    },
    async submit() {
      let dayTime = this.getTimestamp(this.daytime);
      if (this.chosenAddressId) {
        console.log(this.userInfo.balance - this.total);
        if (this.userInfo.balance - this.total >= 0) {
          let data = {
            addressId: this.chosenAddressId,
            customerId: this.userInfo.id,
            orderLines: Array.from(this.orderLines.values()),
            serviceTime: dayTime,
          };
          let data2 = {
            // id: this.userInfo.id,
            // balance:this.userInfo.balance - this.total
            id: this.userInfo.id,
            username: this.userInfo.username,
            password: this.userInfo.password,
            telephone: this.userInfo.telephone,
            realname: this.userInfo.realname,
            gender: this.userInfo.gender,
            birth: this.userInfo.birth,
            email: this.userInfo.email,
            status: this.userInfo.status,
            userFace: this.userInfo.userFace,
            registerTime: this.userInfo.registerTime,
            nation: this.userInfo.nation,
            idCard: this.userInfo.idCard,
            idcardPhotoPositive: this.userInfo.idcardPhotoPositive,
            idcardPhotoNegative: this.userInfo.idcardPhotoNegative,
            bankCard: this.userInfo.bankCard,
            bankCardPhoto: this.userInfo.bankCardPhoto,
            balance: this.userInfo.balance - this.total,
            certificationStatus: this.userInfo.balance,
            certificationTime: this.userInfo.certificationTime,
          };
          let res = await post_json("/order/submitOrder", data);
          let res2 = await post("/baseUser/saveOrUpdate", data2);
          // 将拿到的数据赋值给轮播图数组
          console.log("提交成功");
          this.$router.push({
            path: 'order',
          });
        } else {
          console.log("提交失败");
        }
      } else {
        console.log("提交失败");
      }
    },
    getTimestamp(time) {
      //把时间日期转成时间戳 方法
      return new Date(time).getTime();
    },
  },
  created() {
    this.daytime = String(new Date());
    this.getAddressData().then((res) => {
      this.content[0] = res.data.data.list[0].username;
      this.content[1] = res.data.data.list[0].telephone;
      this.content[2] =
        res.data.data.list[0].province +
        res.data.data.list[0].city +
        res.data.data.list[0].area +
        res.data.data.list[0].address;
      console.log(this.content);
    });
    this.getUserInfo();
  },
  mounted() {
    //   this.content = "姓名"+this.addressData.list[0].name+"电话"+this.addressData.list[0].telephone+"地址"+this.addressData.list[0].address
  },
};
</script>

<style scoped>
.celladdress,
.cellaorder,
.celltime {
  margin: 10px auto;
  box-shadow: 2px 2px 2px 2px rgba(158, 117, 255, 0.2);
  transition: 0.3s;
  width: 95%;
  border-radius: 5px;
}
</style>